#include <retro.h>
#include "retro.library.h"
#include "retro.d3ddisplay.h"

using namespace Retro;
using namespace Retro::Device;
using namespace Retro::Device::Display;

DisplayDevice* Display::CreateDevice(LibraryType iLibrary)
{
  switch (iLibrary)
  {
  case LibraryD3D:
    return new D3DDisplay();
  }

  return NULL;
}

ResourceBuffer::~ResourceBuffer()
{
  clear();
}

UINT  ResourceBuffer::clean()
{
  for (UINT i = 0; i < mBuffer.getLength(); ++i)
  {
    if (mBuffer[i]->getRefCount() <= 0) {
      Resource* wResource = mBuffer[i];

      mBuffer.remove(i--);
      delete wResource;
    }
  }

  return mBuffer.getLength();
}

VOID  ResourceBuffer::clear()
{
  for (UINT i = 0; i < mBuffer.getLength(); ++i)
  {
    mBuffer[i]->uninitialize();
    delete mBuffer[i];
  }

  mBuffer.clear();
}

Resource* ResourceBuffer::getFromID(INT iID)
{
  for (UINT i = 0; i < mBuffer.getLength(); ++i)
  {
    if (mBuffer[i]->getID() == iID)
      return mBuffer[i];
  }

  return NULL;
}

Resource* ResourceBuffer::getFromResourceID(INT iID)
{
  for (UINT i = 0; i < mBuffer.getLength(); ++i)
  {
    if (mBuffer[i]->getResource())
    {
      if (mBuffer[i]->getResource()->getID() == iID)
        return mBuffer[i];
    }
  }

  return NULL;
}

Resource* ResourceBuffer::getFromResourceName(PCTSTR iName)
{
  for (UINT i = 0; i < mBuffer.getLength(); ++i)
  {
    if (mBuffer[i]->getResource())
    {
      if (_tcscmp(mBuffer[i]->getResource()->getName(), iName) == 0)
        return mBuffer[i];
    }
  }

  return NULL;
}

BOOL  ResourceBuffer::remove(INT iIndex)
{
  if (mBuffer[iIndex]->unref() <= 0)
  {
    mBuffer[iIndex]->uninitialize();
    delete mBuffer[iIndex];
    mBuffer.remove(iIndex);

    return TRUE;
  }

  return FALSE;
}

BOOL  ResourceBuffer::remove(Resource* iValue)
{
  for (UINT i = 0; i < mBuffer.getLength(); ++i)
  {
    if (mBuffer[i] == iValue)
      return remove(i);
  }

  return FALSE;
}

BOOL  ResourceBuffer::removeFromID(INT iID)
{
  for (UINT i = 0; i < mBuffer.getLength(); ++i)
  {
    if (mBuffer[i]->getID() == iID)
      return remove(i);
  }

  return FALSE;
}

BOOL  ResourceBuffer::removeFromResourceID(INT iID)
{
  for (UINT i = 0; i < mBuffer.getLength(); ++i)
  {
    if (mBuffer[i]->getResource()->getID() == iID)
      return remove(i);
  }

  return FALSE;
}

BOOL  ResourceBuffer::removeFromName(PCTSTR iName)
{
  for (UINT i = 0; i < mBuffer.getLength(); ++i)
  {
    if (_tcscmp(mBuffer[i]->getResource()->getName(), iName) == 0)
      return remove(i);
  }

  return FALSE;
}
